﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using DAL;
using Common;
using System.Data.Linq;
using System.Linq.Expressions;
namespace BAL
{
    public class RoleMenu
    {
        internal static RoleMenuInfo TransRoleMenu2RoleMenuInfo(Models.Role_Menu roleMenu)
        {
            RoleMenuInfo roleMenuInfo = new RoleMenuInfo();

            Utility.SetObjectValueWithTheSamePropertyName(roleMenuInfo, roleMenu);

            return roleMenuInfo;
        }

        public static bool CheckRoleMenuExist(int mid, int rid)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                IList<Expression<Func<Models.Role_Menu, bool>>> funcs = new List<Expression<Func<Models.Role_Menu, bool>>>();
                funcs.Add(w => w.RoleId == rid);
                funcs.Add(w => w.MenuId == mid);
                if (funcs.Count > 0)
                {
                    IQueryable<Models.Role_Menu> iqueryable = db.Role_Menus.Where(funcs[0]);
                    for (int i = 1; i < funcs.Count; i++)
                    {
                        iqueryable = iqueryable.Where(funcs[i]);
                    }
                    if (iqueryable.Skip(0).Take(int.MaxValue).Count() > 0)
                        return true;
                    else
                        return false;
                }
                return false;
            }
        }

        public static IList<RoleMenuInfo> GetRoleMenuInfos(int rid)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                return db.Role_Menus.Where(w => w.RoleId == rid).Select(w => TransRoleMenu2RoleMenuInfo(w)).ToList();
            }
        }

        public static void DelRoleMenu(int id)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                DelRoleMenu(new int[] { id });
            }
        }

        public static void DelRoleMenu(int[] lstId)
        {
            using (var db = DatabaseHelper.GetDashboardData())
            {
                if (lstId.Length > 0)
                {
                    string sql = string.Format("delete from Role_Menu where RoleId in ({0})", string.Join(",", lstId.ConvertToStringArray()));
                    db.ExecuteCommand(sql);
                }
            }
        }
        public static RoleMenuInfo AddRoleMenu(RoleMenuInfo roleMenuInfo)
        {
            Models.Role_Menu rolemenu = new Models.Role_Menu();
            Utility.SetObjectValueWithTheSamePropertyName(rolemenu, roleMenuInfo);
            DatabaseHelper.Insert<Models.Role_Menu>(rolemenu);
            return TransRoleMenu2RoleMenuInfo(rolemenu);
        }
    }
}
